package com.danskin.wechat.api.client;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.danskin.wechat.dto.CRMMemberRequest;
import com.danskin.wechat.util.EncryptUtil;
import com.danskin.wechat.util.PropertyUtil;

public class DanskinCRMApiClient extends ApiClient {

	private static final String CRM_APP_SECRET = PropertyUtil.get("crm_api_secret");
	private static final String CRM_API_URL = PropertyUtil.get("crm_api_url"); // CRM接口地址

	private volatile static DanskinCRMApiClient singleton;

	private DanskinCRMApiClient() {
	}

	public static DanskinCRMApiClient createInstance() {
		if (singleton == null) {
			synchronized (DanskinCRMApiClient.class) {
				if (singleton == null) {
					singleton = new DanskinCRMApiClient();
				}
			}
		}
		return singleton;
	}

	/**
	 * 新增会员信息
	 * 
	 * @param mobile
	 *            手机号
	 * @param brandId
	 *            品牌Id
	 * @return JSON实体
	 */
	public JSONObject addMember(CRMMemberRequest crmMember) {

		JSONObject memberInfo = new JSONObject();
		memberInfo.put("mobileNum", crmMember.getMobile());
		memberInfo.put("cardNum", crmMember.getCardNum());// 微信卡号是手机号
		memberInfo.put("brand", crmMember.getBrandId());
		if (StringUtils.isNotBlank(crmMember.getFullName())) {
			memberInfo.put("fullName", crmMember.getFullName());
		}
		if (StringUtils.isNotBlank(crmMember.getIdNum())) {
			memberInfo.put("idNum", crmMember.getIdNum());
		}
		String gender = crmMember.getGender();
		if (StringUtils.isNotBlank(gender) && !gender.equals("0")) {
			memberInfo.put("gender", gender.equals("1") ? "男" : "女");
		} else {
			memberInfo.put("gender", "");
		}
		if (StringUtils.isNotBlank(crmMember.getBirthday())) {
			memberInfo.put("birthday", crmMember.getBirthday());
		}
		if (StringUtils.isNotBlank(crmMember.getHobby())) {
			memberInfo.put("hobby", crmMember.getHobby());
		}
		if (StringUtils.isNotBlank(crmMember.getProvince())) {
			memberInfo.put("province", crmMember.getProvince());
		}
		if (StringUtils.isNotBlank(crmMember.getCity())) {
			memberInfo.put("city", crmMember.getCity());
		}
		if (StringUtils.isNotBlank(crmMember.getAddress())) {
			memberInfo.put("address", crmMember.getAddress());
		}
		// if (StringUtils.isNotBlank(crmMember.getIncome())) {
		// memberInfo.put("income", crmMember.getIncome());
		// }
		// if (StringUtils.isNotBlank(crmMember.getJob())) {
		// memberInfo.put("job", crmMember.getJob());
		// }
		// if (StringUtils.isNotBlank(crmMember.getQq())) {
		// memberInfo.put("qqNum", crmMember.getQq());
		// }

		JSONObject businessParameters = new JSONObject();
		businessParameters.put("memberJSONList", memberInfo);

		return this.invokeApi("AddMemberPTC", businessParameters);
	}

	/**
	 * 修改会员信息
	 * 
	 * @param memberId
	 *            会员编号
	 * @param memberlevel
	 *            会员等级
	 * @param name
	 *            姓名
	 * @param mobile
	 *            手机号
	 * @param birthday
	 *            生日
	 * @param hobby
	 *            爱好
	 * @param province
	 *            省（代码）
	 * @param city
	 *            市（代码），如果是直辖市，传区的code
	 * @param brandId
	 *            品牌Id
	 * @return JSON实体
	 */
	public JSONObject modifyMember(CRMMemberRequest crmMember) {

		JSONObject memberInfo = new JSONObject();
		memberInfo.put("memberId", crmMember.getMemberId());
		memberInfo.put("memberLevel", crmMember.getMemberlevel());
		memberInfo.put("fullName", crmMember.getFullName());
		String gender = crmMember.getGender();
		if (StringUtils.isNotBlank(gender) && !gender.equals("0")) {
			memberInfo.put("gender", gender.equals("1") ? "男" : "女");
		} else {
			memberInfo.put("gender", "");
		}
		memberInfo.put("mobileNum", crmMember.getMobile());
		memberInfo.put("birthday", crmMember.getBirthday());
		memberInfo.put("hobby", crmMember.getHobby());
		memberInfo.put("province", crmMember.getProvince());
		memberInfo.put("city", crmMember.getCity());
		memberInfo.put("address", crmMember.getAddress());
		// memberInfo.put("qqNum", crmMember.getQq());
		// memberInfo.put("income", crmMember.getIncome());
		// memberInfo.put("job", crmMember.getJob());
		memberInfo.put("brand", crmMember.getBrandId());

		JSONObject businessParameters = new JSONObject();
		businessParameters.put("memberJSONList", memberInfo);

		return this.invokeApi("ModifyMemberPTC", businessParameters);
	}

	/**
	 * 调用CRM请求发积分
	 * 
	 * @param changeId
	 * @param memberId
	 * @param mobile
	 * @param value
	 * @param changeReason
	 * @return
	 * @author makunsmac
	 */
	public JSONObject sendPointToCRM(String changeId, String memberId, String mobile, float value, String changeReason,
			String brandId) {
		JSONObject pointInfo = new JSONObject();
		pointInfo.put("changeId", changeId);
		pointInfo.put("memberid", memberId);
		pointInfo.put("mobile", mobile);
		pointInfo.put("value", value);
		pointInfo.put("changeReason", changeReason);
		pointInfo.put("brand", brandId);

		JSONObject businessParameters = new JSONObject();
		businessParameters.put("changeJSONList", pointInfo);

		return this.invokeApi("ModifyIntergralWTC", businessParameters);
	}

	/**
	 * 调用CRM请求发券
	 * 
	 * @param memberid
	 * @param couponTemplateID
	 * @param counts
	 * @param value
	 * @return
	 */
	public JSONObject sendCouponToCRM(String memberid, String couponTemplateID, Integer counts, String campaginName,
			String brandId) {
		JSONObject couponInfo = new JSONObject();
		couponInfo.put("memberid", memberid);
		couponInfo.put("couponTemplateID", couponTemplateID);
		couponInfo.put("counts", counts);
		couponInfo.put("value", 0);
		couponInfo.put("brand", brandId);

		JSONObject businessParameters = new JSONObject();

		businessParameters.put("campaginName", campaginName);
		businessParameters.put("BuyJSONList", couponInfo);

		return invokeApi("SendCouponByCampagin", businessParameters);
	}

	/**
	 * 积分换卡/优惠券
	 * 
	 * @param crmMember
	 * @param couponTemplateId
	 * @param num
	 * @param points
	 * @return
	 */
	public JSONObject pointBuyCoupon(CRMMemberRequest crmMember, String couponTemplateId, int num, int points) {

		JSONObject memberInfo = new JSONObject();
		memberInfo.put("memberid", crmMember.getMemberId());
		memberInfo.put("customerMobile", crmMember.getMobile());
		memberInfo.put("couponTemplateID", couponTemplateId);
		memberInfo.put("counts", num);
		memberInfo.put("value", points);
		memberInfo.put("brand", crmMember.getBrandId());

		JSONObject businessParameters = new JSONObject();
		businessParameters.put("BuyJSONList", memberInfo);

		return this.invokeApi("BuyCoupon", businessParameters);
	}

	public JSONObject getMemberIdByPosCardNo(String brandId, String posCardNo) {

		JSONObject businessParameters = new JSONObject();
		businessParameters.put("cardNo", posCardNo);
		businessParameters.put("brand", brandId);

		return this.invokeApi("GetMemberID", businessParameters);
	}

	private JSONObject invokeApi(String method, JSONObject businessParameters) {

		String data = getSecretParams(businessParameters).toJSONString();

		return sendPost(CRM_API_URL + method, data);
	}

	private JSONObject getSecretParams(JSONObject result) {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		Date now = new Date();
		result.put("signdate", df.format(now));

		String secret = EncryptUtil.MD5((now.getTime() / 1000) + CRM_APP_SECRET).toLowerCase();
		result.put("secret", secret);

		return result;
	}

	public static void main(String[] args) {
		CRMMemberRequest r = new CRMMemberRequest();
		r.setMemberId("ece7d3f9933a40329fe34c156b3860a8");
		r.setMemberlevel("v1");// 会员等级需要字段？
		r.setFullName("王磊");
		r.setGender("2");
		r.setMobile("15801387336");
		r.setCardNum("15801387336");
		r.setBirthday("2017-10-10");
		r.setHobby("football,basketball");
		r.setProvince("110000");
		r.setCity("110101");
		r.setAddress("上海鲁班路558号2");
		r.setBrandId("1");

		// DanskinCRMApiClient.createInstance().addMember(r);
		//
		// DanskinCRMApiClient.createInstance().modifyMember(r);

		// DanskinCRMApiClient.createInstance().sendPointToCRM("123456",
		// r.getMemberId(), r.getMobile(), -10, "新人礼", r.getBrandId());

		// DanskinCRMApiClient.createInstance().sendCouponToCRM(r.getMemberId(),
		// "100001", 2, "新人礼活动", r.getBrandId());

		// DanskinCRMApiClient.createInstance().pointBuyCoupon(r, "100001", 2,
		// 10);

		DanskinCRMApiClient.createInstance().getMemberIdByPosCardNo("1", "LE013070455676D27");
		String md5 = EncryptUtil.MD5("kuige");

		System.out.println(md5);
	}
}
